"""
成交量图绘制模块
负责成交量图的绘制和显示
"""

import pyqtgraph as pg
from typing import List, Tuple, Optional

from .config import config, flags


class VolumeChart:
    """成交量图管理类"""
    
    def __init__(self, plot_widget: pg.PlotWidget):
        """
        初始化成交量图
        
        Args:
            plot_widget: PyQtGraph绘图控件
        """
        if flags.ENABLE_VOLUME_CHART:
            self.plot_widget = plot_widget
            self.volume_bars: Optional[pg.BarGraphItem] = None
            self.volume_data: Optional[Tuple[List[int], List[float], List[str]]] = None
            
            # 设置图表基本属性
            self._setup_plot()
    
    def _setup_plot(self):
        """设置图表基本属性"""
        if not flags.ENABLE_VOLUME_CHART:
            return
        self.plot_widget.setTitle("成交量")
        self.plot_widget.showGrid(x=config.SHOW_GRID_X, y=config.SHOW_GRID_Y)
        self.plot_widget.vb.disableAutoRange()
    
    def update_data(self, volume_x: List[int], volume_heights: List[float], 
                   volume_colors: List[str], bar_width: float = 0.8):
        """
        更新成交量数据
        
        Args:
            volume_x: X坐标列表
            volume_heights: 成交量高度列表
            volume_colors: 颜色列表
            bar_width: 柱状图宽度
        """
        if not flags.ENABLE_VOLUME_CHART:
            return
        self.volume_data = (volume_x, volume_heights, volume_colors)
        
        # 移除旧的成交量柱状图
        if self.volume_bars is not None:
            self.plot_widget.removeItem(self.volume_bars)
        
        # 创建新的成交量柱状图
        self.volume_bars = pg.BarGraphItem(
            x=volume_x,
            height=volume_heights,
            width=bar_width,
            brushes=volume_colors,
            pens=volume_colors
        )
        self.plot_widget.addItem(self.volume_bars)
    
    def scale_volume_to_price(self, max_volume: float, max_price: float, 
                            scale_factor: float = 1000):
        """
        将成交量按价格比例缩放
        
        Args:
            max_volume: 最大成交量
            max_price: 最大价格
            scale_factor: 缩放因子
        """
        if not flags.ENABLE_VOLUME_CHART:
            return
        if self.volume_data is None:
            return
        
        volume_x, volume_heights, volume_colors = self.volume_data
        
        # 归一化成交量到 [0,1]
        if max_volume > 0:
            normalized_heights = [h / max_volume for h in volume_heights]
        else:
            normalized_heights = [0] * len(volume_heights)
        
        # 按价格比例缩放
        scaled_heights = [h * scale_factor * max_price for h in normalized_heights]
        
        # 更新数据
        self.update_data(volume_x, scaled_heights, volume_colors)
    
    def set_volume_range(self, min_volume: float, max_volume: float, 
                        compression_factor: float = 0.2, padding: float = 0.05):
        """
        设置成交量范围
        
        Args:
            min_volume: 最小成交量
            max_volume: 最大成交量
            compression_factor: 压缩因子，用于减少视觉上的高低差异
            padding: 边距
        """
        if not flags.ENABLE_VOLUME_CHART:
            return
        volume_range = max_volume - min_volume
        y_min = min_volume
        y_max = min_volume + volume_range * compression_factor
        self.plot_widget.setYRange(y_min, y_max, padding=padding)
    
    def set_x_range(self, x_min: float, x_max: float):
        """
        设置X轴范围
        
        Args:
            x_min: X轴最小值
            x_max: X轴最大值
        """
        if not flags.ENABLE_VOLUME_CHART:
            return
        self.plot_widget.setXRange(x_min, x_max)
    
    def set_date_ticks(self, date_ticks: List[Tuple[int, str]]):
        """
        设置X轴日期刻度
        
        Args:
            date_ticks: 日期刻度列表
        """
        if not flags.ENABLE_VOLUME_CHART:
            return
        axis = self.plot_widget.getAxis('bottom')
        axis.setTicks([date_ticks])
    
    def link_x_axis(self, other_plot):
        """
        链接X轴到另一个图表
        
        Args:
            other_plot: 要链接的图表
        """
        if not flags.ENABLE_VOLUME_CHART:
            return
        self.plot_widget.setXLink(other_plot)
    
    def get_plot_widget(self) -> pg.PlotWidget:
        """获取绘图控件"""
        if not flags.ENABLE_VOLUME_CHART:
            return None
        return self.plot_widget
